package cn.com.pc.content.converter;

import lombok.SneakyThrows;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.core.convert.converter.Converter;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Spring MVC Date转换
 */
public class DateConverter implements Converter<String, Date> {
    private static final List<String> formarts = new ArrayList<>(4);
    static{
        formarts.add("yyyy-MM");
        formarts.add("yyyy-MM-dd");
        formarts.add("yyyy-MM-dd hh:mm");
        formarts.add("yyyy-MM-dd hh:mm:ss");
        formarts.add("yyyy/MM");
        formarts.add("yyyy/MM/dd");
        formarts.add("yyyy/MM/dd hh:mm");
        formarts.add("yyyy/MM/dd hh:mm:ss");
    }

    @SneakyThrows
    @Override
    public Date convert(String source) {
        String value = source.trim();
        if ("".equals(value)) {
            return null;
        }
        if(source.matches("^\\d{4}-\\d{1,2}$")){
            return DateUtils.parseDate(source, formarts.get(0));
        }else if(source.matches("^\\d{4}-\\d{1,2}-\\d{1,2}$")){
            return DateUtils.parseDate(source, formarts.get(1));
        }else if(source.matches("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}$")){
            return DateUtils.parseDate(source, formarts.get(2));
        }else if(source.matches("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}:\\d{1,2}$")){
            return DateUtils.parseDate(source, formarts.get(3));
        }else if(source.matches("^\\d{4}/\\d{1,2}$")){
            return DateUtils.parseDate(source, formarts.get(4));
        }else if(source.matches("^\\d{4}/\\d{1,2}/\\d{1,2}$")){
            return DateUtils.parseDate(source, formarts.get(5));
        }else if(source.matches("^\\d{4}/\\d{1,2}/\\d{1,2} {1}\\d{1,2}:\\d{1,2}$")){
            return DateUtils.parseDate(source, formarts.get(6));
        }else if(source.matches("^\\d{4}/\\d{1,2}/\\d{1,2} {1}\\d{1,2}:\\d{1,2}:\\d{1,2}$")){
            return DateUtils.parseDate(source, formarts.get(7));}
        else{
            throw new IllegalArgumentException("Invalid LocalDateTime value '" + source + "'");
        }
    }

}
